<!--
  功能：题库管理
  作者：licy
  邮箱：licy@briup.com
  时间：2021年01月13日 14:15:00
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->

<template>
  <div class='question_list'>
    <div class="page_header">
      <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
    </div>
    <!-- 按钮区域 -->
    <div class="btns">
      <el-row>
        <el-col :span="16">
          <el-form inline size="small">
            <el-form-item label="名称">
              <el-input v-model="param.name" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="loadQuestion">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" style="text-align:right">
          <el-button type="primary" size="small" @click="toBatchImportHandler">批量导入</el-button>
          <el-button type="primary" size="small" @click="toSaveHandler">创建题目</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 按钮区域结束 -->
    <!-- 表格 -->
    <el-table size="small" :data="questionData.list" v-loading="loading" class="question_table">
      <el-table-column label="序号" type="index" :index="1"></el-table-column>
      <el-table-column label="题干"> 
        <template v-slot="scope">
          <div v-html="scope.row.name"></div>
        </template>
      </el-table-column>
      <el-table-column label="类型" prop="type" width="80" align="center"> </el-table-column>
      <el-table-column label="难度" prop="level" width="80" align="center"> </el-table-column>
      <!-- <el-table-column label="标签" prop="label" width="80" align="center"> </el-table-column> -->
      <!-- <el-table-column label="通过率" prop="ratioPass" width="80" align="center"> </el-table-column> -->
       <el-table-column  label="创建时间" width="120" align="center">
          <template slot-scope="scope">
            {{scope.row.createTime | fmtDate}}
          </template>
        </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="toEditQuestionHandler(scope.row)">修改</el-button>
          <el-button type="text" size="mini" @click="toQuestionDetailsHandler(scope.row)">查看</el-button>
          <el-button type="text" size="mini" @click="toDeleteHandler(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格结束 -->
    <!-- 分页 -->
   <div class="page">
      <el-pagination background 
        layout="prev, pager, next,sizes" 
        small
        :total="questionData.total" 
        :page-size="questionData.pageSize" 
        :current-page="questionData.page"
        :page-sizes="[5, 10, 15, 20]"
        @size-change="handleSizeChange"
        @current-change="currentChangeHandler">
      </el-pagination>
   </div>
    <!-- 分页 -->
    <!-- 抽屉 -->
    <Briupdrawer :drawer-visible="visible" :title="title" width="50%" @on-change-visible="handlerVisibleChange" >
      <div slot="content">
        <el-form ref="form" :rules='rules' :model="form" label-position='left' size='small'>
            <el-form-item label="题目名称"  prop="question.name">
                <tinymce v-model="form.question.name" :height="240"  v-if="visible" style="clear:both"/>
            </el-form-item>
            <el-form-item label="难度级别"  prop="question.level">
              <div style="clear:left">
                <el-radio-group v-model="form.question.level">
                  <el-radio label="入门">入门</el-radio>
                  <el-radio label="简单">简单</el-radio>
                  <el-radio label="中等">中等</el-radio>
                  <el-radio label="较难">较难</el-radio>
                  <el-radio label="困难">困难</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item label="题目类型"  prop="question.type">
              <div style="clear:left">
                <el-radio-group v-model="form.question.type">
                  <el-radio label="单选">单选</el-radio>
                  <el-radio label="多选">多选</el-radio>
                  <el-radio label="判断">判断</el-radio>
                  <el-radio label="问答">问答</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item v-if='form.question.type =="单选" || form.question.type =="多选"' label="题目选项" prop="descriptioin">
              <el-table :data='form.options' size='mini' border>
                <el-table-column label='序号' type="index" :index="1" width='60' align='center'> </el-table-column>
                <el-table-column prop='label' label='label' width='60' align='center'></el-table-column>
                <el-table-column label='选项'>
                  <template slot-scope='scope'>
                    <el-input v-model='scope.row.name' size="mini"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label='设置正确答案'  width='100' align='center'>
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.isCorrect" @change="isCorrectChangeHandler" size="mini" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#ff4949"> </el-switch>
                  </template>
                </el-table-column>
                <!-- <el-table-column label='操作'  width='60' align='center'>
                  <template slot-scope='scope'>
                    <el-button size="mini" plain type="danger" @click="toDeleteOptionHandler(scope.row)">
                      <em class="el-icon-delete"></em>
                    </el-button>
                  </template>
                </el-table-column> -->
              </el-table>
              <div style='text-align:right;'>
                <el-button type="text" :disabled='form.options.length>=5' size='mini' @click='addOption'>添加</el-button>
              </div>
            </el-form-item>

            <el-form-item v-if='form.question.type =="判断"' label="正确答案"  prop="question.isCorrect">
              <div style="clear:both">
                <el-radio-group v-model="form.question.isCorrect">
                  <el-radio :label="1">正确</el-radio>
                  <el-radio :label="0">错误</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>

            <el-form-item label="答案解析"  prop="question.analysis">
              <tinymce v-model="form.question.analysis" :height="240" v-if="visible" style="clear:both"/>
            </el-form-item>
          </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">取消</el-button>
        <el-button size="small" type="primary" @click="submitHandler">确定</el-button>
      </span>
    </Briupdrawer>
    <!-- 抽屉结束 -->
    <!-- 模态框 -->
    <el-dialog title="题目详情" :visible.sync="dialogVisible" width="60%" class="customer_modal">
      <div class="question_details">
        <div class="title">
          <div v-html="currentQuestion.name"></div>
        </div>
        <div class="info">
          <el-tag size="mini">{{currentQuestion.type}}</el-tag>
          <el-tag size="mini">{{currentQuestion.level}}</el-tag>
        </div>
        <div class="question_content">
          <!-- 选项 -->
          <!-- 单选 -->
          <div class="options" v-if="currentQuestion.type == '单选'">
            <el-radio-group v-model="currentQuestion.answer">
              <el-radio  v-for="option in currentQuestion.options" :key="option.id" :label="option.id">
                {{option.name}}
              </el-radio>
            </el-radio-group>
          </div>
          <!-- 多选 -->
          <div class="options" v-if="currentQuestion.type == '多选'">
            <el-checkbox-group v-model="currentQuestion.answer">
              <el-checkbox  v-for="option in currentQuestion.options" :key="option.id"  :label="option.id">
                {{option.name}}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <!-- 判断 -->
          <div v-if="currentQuestion.type=='判断'">
            <el-radio-group v-model="currentQuestion.isCorrect">
              <el-radio :label="1"><i class="el-icon-check"></i></el-radio>
              <el-radio :label="0"><i class="el-icon-close"></i></el-radio>
            </el-radio-group>
          </div>
          <!-- 问答 -->
          <div v-if="currentQuestion.type == '问答'">
            <el-input type="textarea" :rows="4" ></el-input>
          </div>
        </div>
        <div class="analysis">
          <div v-html="currentQuestion.analysis"></div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer" >
        <div style="text-align:center">
         <el-button @click="dialogVisible = false" type="primary" size="small">关闭</el-button>
        </div>
      </span>
    </el-dialog>
    <!-- /模态框 -->
  </div>
</template>

<script>
import {get,post,postJSON} from '@/utils/request'
import _ from 'lodash'
import Tinymce from '@/components/Tinymce'
export default {
  components: { Tinymce },
  // 组件名称
  name: 'demo',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data () {
   return {
    pageTitle:"",
    questionBankId:null,
    visible:false,
    dialogVisible:false,
    loading:false,
    title:"",
    param:{
      page:1,
      pageSize:10
    },
    questionData:{
      list:[]
    },
    form:{
      question:{},
      options:[]
    },
    rules:{
      'question.name': [ { required: true, message: '请输入题干', trigger: 'blur' } ],
      'question.level': [ { required: true, message: '请选择难度级别', trigger: 'blur' } ],
      'question.type': [ { required: true, message: '请选择类型', trigger: 'blur' } ],
      'question.answer': [ { required: true, message: '请输入答案解析', trigger: 'blur' } ],
      'question.isCorrect': [ { required: true, message: '请选择正确答案', trigger: 'blur' } ]
    },
    question:{} // 当前问题
   }
  },
  // 计算属性
  computed: {
    currentQuestion(){
      let question = this.question;
      switch(question.type){
        case "单选":
          question.answer = +question.answer;
          break;
        case "多选":
          let answers = question.answer.split(",")
          let arr = [];
          for(let a of answers){
            arr.push(+a)
          }
          question.answer = arr;
          break;
        default:
          break;
      }
      return question;
    }
  },
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    // 修改
    toEditQuestionHandler(row){
      let qos = _.clone(row);
      this.title = "新增题目信息";
      this.form = {question:qos,options:qos.options};
      this.visible = true;
    },
    // 批量导入
    toBatchImportHandler(){
      this.$message({type:"warning",message:'该功能还未提供！'})
      // this.$router.push({ path:'/sms/professor/exam/QuestionImport' })
    },
    // 设置正确按钮发生变化
    isCorrectChangeHandler(val){
      
    },
    // 查看题目详情
    toQuestionDetailsHandler(row){
      this.question = row;
      this.dialogVisible = true;
    },
    // 添加选项
    addOption(){
      let option = {};
      let label = ''
      switch(this.form.options.length){
        case 0:
          label='A'; 
          break;
        case 1:
          label='B';
          break;
        case 2:
          label='C'; 
          break;
        case 3:
          label='D'; 
          break;
        case 4:
          label='E';
          break;
      }
      option.label = label;
      option.isCorrect = 0;
      this.form.options.push(option);
    },
    goBack(){
      this.$router.go(-1);
    },
    //查找该题库下所有的题目
    loadQuestions(){
      let url = "/exam/question/pageQuery";
      get(url)
    },
    // 上传成功
    uploadSuccessHandler(response){
      if(response.status == 200){
        this.$set(this.form,'photo',response.data.id);
      } else {
        this.$message({type:'error',message:'附件服务器异常！'})
        this.visible = false;
      }
    },
    // 确认提交处理函数
    submitHandler(){
      // 表单校验
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 校验通过后，完成数据交互
          let url = '/exam/question/saveOrUpdate'
          this.form.question.questionBankId = this.questionBankId;
          if(this.form.question.type == '单选'){
            let corrects = this.form.options.filter(item => {
              return item.isCorrect == 1
            })
            if(corrects.length != 1){
              this.$message({type:"warning",message:"单选题的正确答案只能设置一个"})
              return false;
            }
          }
          postJSON(url,this.form).then(response => {
            this.$message({type:"success",message:response.message})
            this.loadQuestion();
            this.visible = false;
          })
        } else {
          return false;
        }
      });
    },
    // 去保存
    toSaveHandler(){
      this.title = "新增题目信息";
      this.form = {question:{},options:[]};
      // 默认产生3个选项
      this.addOption();
      this.addOption();
      this.addOption();
      this.visible = true;
    },
    // 去删除
    toDeleteHandler(row){
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = '/exam/question/deleteById'
        get(url,{id:row.id}).then(response =>{
          this.$message({ type: 'success', message: '删除成功!' });
          this.loadQuestion();
        })
      })
    },
    // 查询题目信息
    loadQuestion(){
      // 添加loading,页面加载开始
      this.loading = true;
      let url = "/exam/question/pageQuery"
      this.param.questionBankId = this.questionBankId;
      get(url,this.param).then(response => {
        this.questionData = response.data;
        // 页面加载结束
        this.loading = false;
      })
    },
    // 当前页发生改变
    currentChangeHandler(page){
      this.param.page = page;
      this.loadQuestion();
    },
    // 处理分页大小变化的函数
    handleSizeChange(pageSize){
      // 当前页为第一页
      this.page = 1;
      // 页面大小为用户选择的页面
      this.param.pageSize = pageSize;
      this.loadQuestion();
    },
    // 重置表单校验
    clearValidate() {
      this.$refs['form'].clearValidate();
    },
    // 处理visible变化的钩子函数，解决抽屉无法收缩的bug
    handlerVisibleChange(val) {
      this.visible = val
    }
  },
  // 以下是生命周期钩子
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
  */
  created () {
    this.pageTitle = this.$route.query.name;
    this.questionBankId = this.$route.query.id;
    // 加载题目信息
    this.loadQuestion();
  },
  /**
  * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
  */
  mounted () {
  },
  /**
  * 实例销毁之前调用。在这一步，实例仍然完全可用。
  */
  beforeDestroy () {
  },
  /**
  * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
  * 所有的事件监听器会被移除，所有的子实例也会被销毁。
  */
  destroyed () {
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style lang="scss" scoped>
.question_details {
  .title {
    line-height: 2em;
    font-weight: bold;
  }
  .info {
    padding:.5em 0
  }
}

.question_table img {
  width: 200px;
}
</style>
